package com.cskaoyan.order.service.impl;

import com.cskaoyan.mall.commons.constant.SysRetCodeConstants;
import com.cskaoyan.mall.commons.exception.ExceptionProcessorUtils;
import com.cskaoyan.mall.order.constant.OrderRetCode;
import com.cskaoyan.order.conf.OrderProperties;
import com.cskaoyan.order.converter.OrderConverter;
import com.cskaoyan.order.dal.entitys.Order;
import com.cskaoyan.order.dal.entitys.OrderItem;
import com.cskaoyan.order.dal.entitys.OrderShipping;
import com.cskaoyan.order.dal.persistence.OrderItemMapper;
import com.cskaoyan.order.dal.persistence.OrderMapper;
import com.cskaoyan.order.dal.persistence.OrderShippingMapper;
import com.cskaoyan.order.dto.*;
import com.cskaoyan.order.form.OrderDetail;
import com.cskaoyan.order.service.OrderQueryService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

/**
 * @author Chen_Feng
 * @since 2022/07/09 19:40
 */
@Slf4j
@Service
@Data
public class OrderQueryServiceImpl implements OrderQueryService {

    @Autowired
    OrderProperties orderProperties;

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    OrderItemMapper orderItemMapper;

    @Autowired
    OrderConverter orderConverter;

    @Autowired
    OrderShippingMapper orderShippingMapper;


    /**
     * 分页查询所有订单
     *
     * @param orderListRequest 请求对象
     * @return com.cskaoyan.order.dto.OrderListResponse
     * @author Chen_Feng
     * @since 2022/07/09 17:42
     */
    @Override
    @Transactional
    public OrderListResponse orderList(OrderListRequest orderListRequest) {
        OrderListResponse response = new OrderListResponse();
        try {
            // 开启分页
            PageHelper.startPage(orderListRequest.getPage(), orderListRequest.getSize());

            // 查询订单
            List<Order> orderList = null;
            // Example orderExample = new Example(Order.class);
            // orderExample.setOrderByClause("create_time desc");
            // Example.Criteria criteria = orderExample.createCriteria();
            // criteria.andEqualTo("userId", orderListRequest.getUserId());
            // if (orderProperties.isDeletedFieldExist()) {
            //     criteria.andEqualTo("deleted", false);
            // }
            Long userId = orderListRequest.getUserId();
            orderList = orderMapper.selectListByUserId(userId, orderProperties.isDeletedFieldExist());

            // 获得总记录数
            PageInfo<Order> orderPageInfo = new PageInfo<>(orderList);

            /*
            // 查询订单
            List<Order> orderList = null;
            try {
                Example orderExample = new Example(Order.class);
                orderExample.createCriteria()
                        .andEqualTo("userId", orderListRequest.getUserId())
                        .andEqualTo("deleted", false);
                orderList = orderMapper.selectByExample(orderExample);
            } catch (Exception e) {
                log.debug("==========tb_order表无deleted字段,现已忽略该字段重新查询===========");
                e.printStackTrace();
                Example orderExample = new Example(Order.class);
                orderExample.createCriteria()
                        .andEqualTo("userId", orderListRequest.getUserId());
                orderList = orderMapper.selectByExample(orderExample);
            }
            */

            // 查询订单中的商品
            List<OrderDetailInfo> orderDetailInfoList = orderConverter.orderList2ODetailList(orderList);
            wrapItemAndShippingToOrderDetailInfo(orderDetailInfoList);

            // 封装响应数据
            response.setTotal(orderPageInfo.getTotal());
            response.setDetailInfoList(orderDetailInfoList);
            response.setCode(OrderRetCode.SUCCESS.getCode());
            response.setMsg(OrderRetCode.SUCCESS.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
        }
        return response;
    }

    /**
     * 根据订单id查询订单详情
     *
     * @param request 带有订单id的request对象
     * @return com.cskaoyan.order.dto.OrderDetailResponse
     * @author Chen_Feng
     * @since 2022/07/09 20:08
     */
    @Override
    @Transactional
    public OrderDetailResponse orderDetail(OrderDetailRequest request) {

        OrderDetailResponse response = new OrderDetailResponse();

        try {
            // 订单id
            String orderId = request.getOrderId();

            // 根据订单id查询订单详情
            OrderDetail orderDetail = orderMapper.selectOrderDetailByOrderId(orderId, orderProperties.isDeletedFieldExist());

            // 将orderDetail转化为Dto
            OrderDetailDto orderDetailDto = orderConverter.detail2Dto(orderDetail);

            // 封装数据
            response.setCode(SysRetCodeConstants.SUCCESS.getCode());
            response.setMsg(SysRetCodeConstants.SUCCESS.getMessage());
            response.setOrderDetailDto(orderDetailDto);
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
        }
        return response;
    }

    /**
     * 根据orderDetail对象中的orderId查询订单商品信息和物流信息
     * 并将这些信息封装进orderDetail对象中
     *
     * @param orderDetailInfoList
     * @return void
     * @author Chen_Feng
     * @since 2022/07/10 23:40
     */
    private void wrapItemAndShippingToOrderDetailInfo(List<OrderDetailInfo> orderDetailInfoList) {
        for (OrderDetailInfo orderDetailInfo : orderDetailInfoList) {

            // 根据订单id查询订单商品
            String orderId = orderDetailInfo.getOrderId();
            Example orderItemExample = new Example(OrderItem.class);
            orderItemExample.createCriteria().andEqualTo("orderId", orderId);
            List<OrderItem> orderItemList = orderItemMapper.selectByExample(orderItemExample);

            // 将订单商品List转化为Dto的List,并赋值给OrderDetailInfo
            List<OrderItemDto> orderItemDtos = orderConverter.item2dto(orderItemList);
            orderDetailInfo.setOrderItemDto(orderItemDtos);

            // 根据订单id查询物流信息
            Example orderShippingExample = new Example(OrderShipping.class);
            orderShippingExample.createCriteria().andEqualTo("orderId", orderId);
            OrderShipping orderShipping = orderShippingMapper.selectOneByExample(orderShippingExample);

            // 将物流信息转化为Dto，赋值给OrderDetailInfo
            OrderShippingDto orderShippingDto = orderConverter.shipping2dto(orderShipping);
            orderDetailInfo.setOrderShippingDto(orderShippingDto);
        }
    }
}
